package com.ljy.my_study.java.juc.phaser;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;

/**
 * @author lijunying
 * @date 2021/2/1 10:07
 */
public class PhaserTestMain2 {

    public static void main(String[] args) {
        List<Runnable> tasks=new ArrayList<>();
        for(int i=0;i<10;i++){
            int num=i;
            Runnable runnable=()->{
                System.out.println("task "+num+" run.");
            };
            tasks.add(runnable);
        }
        PhaserTestMain2 testMain2=new PhaserTestMain2();
        testMain2.runTasks(tasks);
    }

    public void runTasks(List<Runnable> tasks) {
        final Phaser phaser = new Phaser(2); // "1" to register self
        // create and start threads
        List<Thread> threads=new ArrayList<>();
        for (final Runnable task : tasks) {
            phaser.register();
            Thread thread=new Thread() {
                public void run() {
                    phaser.arriveAndAwaitAdvance(); // await all creation
                    task.run();
                }
            };
            thread.start();
            threads.add(thread);
        }


        //如果不加上会阻塞任务执行，对应构造方法传入的parties数
        // allow threads to start and deregister self
        phaser.arriveAndDeregister();
        phaser.arriveAndDeregister();
    }
}
